package com.queming.core.controller;

import com.queming.core.dto.UserCreateDto;
import com.queming.core.dto.UserUpdateDto;
import com.queming.core.mapper.UserMapper;
import com.queming.service.user.UserService;
import com.queming.core.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * @author chencidiao
 * @date 2022/04/17 20:06
 **/
@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(tags = "用户管理接口")
public class UserController {
    /**
     * @author 陈词调
     * @date 2022/4/17
     * 使用这种方式注入只会在用到的时候创建
     */
    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @GetMapping
    @ApiOperation("用户检索")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    Page<UserVo> search(@PageableDefault(sort = {"createdTime"}, direction = Sort.Direction.ASC) Pageable pageable) {
        return userService.search(pageable).map(userMapper::toVo);
    }

    /**
     * @author 陈词调
     * @date 2022/4/19
     * jwt测试接口
     * @Validated:开启字段的验证
     */
    @PostMapping
    @ApiOperation("用户创建")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    UserVo createUser(@Validated @RequestBody UserCreateDto userCreateDto) {
        return userMapper.toVo(userService.create(userCreateDto));
    }

    @GetMapping("/{id}")
    @ApiOperation("获取单个用户")
    UserVo get(@PathVariable String id) {
        return userMapper.toVo(userService.get(id));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @ApiOperation("更新用户信息")
    UserVo update(@PathVariable String id, @Validated @RequestBody UserUpdateDto userUpdateDto) {
        return userMapper.toVo(userService.update(id, userUpdateDto));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    void delete(@PathVariable String id) {
        userService.delete(id);
    }


    @GetMapping("/me")
    UserVo me() {
        return userMapper.toVo(userService.getCurrentUser());
    }

}

